<?php

namespace app\common\model\merchant;

use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 会员导购收货地址表
 */
class MerchantMemberSalesmanAddressModel extends BaseModel
{

    protected $name = 'merchant_member_salesman_address';
    /**
     * 列表
     * @param $where | 条件
     * @return array|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list($where): ?array
    {
        return $this->db()->where($where ?? [])
            ->field('id,area_code,province,city,county,address,real_name,mobile,post_code,def')
            ->order('def desc,id desc')
            ->select();
    }


    /**
     * 列表
     * @param $where | 条件
     * @return array|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info($where): ?array
    {
        return $this->db()->where($where)
            ->field('id,area_code,province,city,county,address,real_name,mobile,post_code,def')
            ->find();
    }

    /**
     * 删除
     * @param $where | 条件
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function del($where)
    {
        return $this->db()->where($where)->delete();
    }

    /**
     * 增加/修改
     * @param array $data
     * @return int
     * @throws DbException
     */
    public function save(array $data)
    {
        $id = $data['id'];
        unset($data['id']);
        $where= [];
        if (!empty($id)){
            $where[] = ['id' , '<>' , $id];
        }
        if ((int)$data['def'] === 1){
            $this->db()->where(['mer_id' => $data['mer_id'], 'user_id' => $data['user_id'] ,'def' => 1])
                ->where($where ?? [])->update(['def' =>  0]);
        }
        if (empty($id)){
            return  $this->db()->allowEmpty(true)->insert($data);
        }
        return  $this->db()->where('id' , $id)->allowEmpty(true)->update($data);
    }
}
